import Taro from '@tarojs/taro';

import { Command } from '../constant';
import { Dispatch } from 'typings';
import { getActionProxy } from '@/redux/action-util';
import * as reduxStore from '@/redux/store';
import packageAddressEditDMain from '../reducers/main';
import { addressInfo } from '@/utils/location/area/area';
import Action from './action';
import api from 'api';

export default (dispatch?: Dispatch) => {
  const actions = {
    action: getActionProxy<typeof Action>(Action)(dispatch),

    /**
     * 初始化数据
     */
    async init(id) {
      let latitude = Taro.getStorageSync('latitude');//纬度
      let longitude = Taro.getStorageSync('longitude');//经度

      const res = await api.customerDeliveryAddressController.findById(id);
      let addressInfoStr;
      if (res.streetId != -1) {
        addressInfoStr = await addressInfo(res.provinceId, res.cityId, res.areaId, res.streetId);
      } else {
        addressInfoStr = await addressInfo(res.provinceId, res.cityId, res.areaId);
      }
      // 调用action中的方法
      // actions.action.test(params);
      // 初始化赋值 后续使用 action 中的commonChange方法改变值
      dispatch({
        type: Command.init, payload: {
          main: {
            latitude: latitude,
            longitude: longitude,
            consigneeName: res.consigneeName,
            consigneeNumber: res.consigneeNumber,
            deliveryAddress: res.deliveryAddress,
            isDefaltAddress: res.isDefaltAddress,
            deliveryAddressId: res.deliveryAddressId,
            areaInfo: addressInfoStr,
            areaIds: [res.provinceId, res.cityId, res.areaId, res.streetId],
            provinceId: res.provinceId,
            cityId: res.cityId,
            areaId: res.areaId,
            streetId: res.streetId,
          },
        },
      })
    },

    /**
     * 重置
     */
    async clean() {
      //@ts-ignore
      __TARO_ENV !== 'h5' && (await actions.unloadReducer());
      dispatch({ type: Command.clean });
    },

    /**
     * 动态添加注入reducer
     */
    async loadReducer() {
      reduxStore.registerReducer({
        packageAddressEditDMain,
      });
    },

    /**
     * 卸载reducer
     */
    async unloadReducer() {
      if (reduxStore.deregister) {
        reduxStore.deregister(['packageAddressEditDMain']);
      } else {
        console.error('请在redux/store中实现deregister逻辑. ');
      }
    },
  };

  return { actions };
};
